import React, { useState, useEffect } from 'react';
import {
  FileExcelOutlined, ProfileOutlined, ReloadOutlined, MinusSquareOutlined,
  PlusSquareOutlined, EditOutlined, ExperimentOutlined, CopyOutlined, ApartmentOutlined,
  UserOutlined, SearchOutlined, EllipsisOutlined, MenuOutlined, CloudUploadOutlined, ToolOutlined
} from '@ant-design/icons';
import { Modal, Select, Button, Spin, Checkbox, DatePicker, Popconfirm, Tree, Input, Row, Col, Card, Divider, Dropdown, Menu, Tabs, Form } from 'antd';
import { createFromIconfontCN } from '@ant-design/icons';
import { useHistory } from 'react-router-dom';
import logo from '../../../img/shipSRM/chlogo.png'
import useStore from '../../useStore.js'
import { clearCache, useDidCache, useDidRecover, dropByCacheKey } from 'react-router-cache-route';

import {
  openNotification_util, fetchsync_util, useexcelauto,
  getCurrentDate_util,
  dealnullorundenfined,
  convertISODateTimeToYYYYMMDDHHMMSS
} from '../util/util.js'
import Custom_table_hooks_config from '../newmes/custom_table_hooks_config.js'
var storage = window.localStorage;
const { Option } = Select;
const { Search } = Input;
import Sortable from '../newmes/sortable.js';
import { use_wlda_initcolmun, use_wlfl_treedata, use_wlda_initcolmun_import } from './use_baseinfo_config.js';
import XLSX from 'xlsx';
import Resizeable_table__hook from '../newmes/Resize_table_hook.js';

const IconFont = createFromIconfontCN({
  scriptUrl: 'http://111.77.154.58:2233/icon.js',
});

// 初始化表格列配置
const initColumns = use_wlda_initcolmun()

const Wlda_list = () => {
  const history = useHistory();
  const [selectedRows, setSelectedRows] = useState([])
  const [selectedRowKeys, setSelectedRowKeys] = useState([])
  const [isLoading, setIsLoading] = useState(false)
  const [treeData, setTreeData] = useState([])
  const [tableData, setTableData] = useState([])
  const [allWldaData, setAllWldaData] = useState([])
  const [allWlflData, setAllWlflData] = useState([])
  const [selectedTreeNode, setSelectedTreeNode] = useState({
    key: 'ship',
    title: '企业物料总目',
    level: 0
  })
  const [expandedKeys, setExpandedKeys] = useState([])
  const [autoExpandParent, setAutoExpandParent] = useState(true)
  const [searchValue, setSearchValue] = useState('')
  const [isTableSettingModalOpen, setIsTableSettingModalOpen] = useState(false) // 表格设置模态框
  const [columnarr, setColumnarr] = useState(initColumns)
  const [initSize, setInitSize] = useState(1)
  const [ifshow, setIfshow] = useState(true)
  
  // 分类管理相关状态
  const [showYjfl, setShowYjfl] = useState(false)  //是否显示一级分类弹窗
  const [showZjfl, setShowZjfl] = useState(false)  //是否显示子级分类弹窗
  const [flmc, setFlmc] = useState("")  //分类名称
  const [flbm, setFlbm] = useState("")  //分类编码

  // 新增分类管理状态
  const [isCategoryModalOpen, setIsCategoryModalOpen] = useState(false)
  const [modalType, setModalType] = useState('') // 'add' or 'edit'
  const [form] = Form.useForm()

  // 导入相关状态
  const [importModalVisible, setImportModalVisible] = useState(false);
  const [excelData, setExcelData] = useState(null);
  const [importloading, setImportloading] = useState(false)
  const [importError, setImportError] = useState([]);
  const [errorRows, setErrorRows] = useState([]);

  const { nowroute, setnowroute, collapsed, setcollapsed } = useStore();

  useEffect(() => {
    queryTreeData()
    queryWldaData()
    storage['Pc_wlda_list'] ? setColumnarr(JSON.parse(storage['Pc_wlda_list'])) : setColumnarr(initColumns)
    storage['Pc_wlda_list_initsize'] ? setInitSize(storage['Pc_wlda_list_initsize']) : setInitSize(1)
  }, [])

  useEffect(() => { ifshow ? "" : setIfshow(true) }, [ifshow])

  // 路由跳转
  const tonormal = (route) => {
    history.push({ pathname: route });
  }

  // 查询物料分类树形数据
  const queryTreeData = async () => {
    setIsLoading(true)
    try {
      let rtdata = await fetchsync_util("/admin/baseinfo/wlfllb", 'POST', {}, "json")
      
      const processedData = dealnullorundenfined(rtdata.resultdata)
      setAllWlflData(processedData)
      console.log('所有分类数据:', processedData.length, '条')
      
      // 构建树形结构
      const treeDataFromApi = buildWlflTree(processedData)
      console.log(treeDataFromApi,"T---R---E---E---D---A---T---A---")
      setTreeData(treeDataFromApi)
      
      // 默认展开根节点
      setExpandedKeys(['ship'])
      
      console.log('分类树初始化完成')
    } catch (error) {
      console.error('查询分类失败:', error);
      openNotification_util('查询分类失败，请稍后重试');
    }
    setIsLoading(false)
  }

  // 查询物料档案数据
  const queryWldaData = async () => {
    setIsLoading(true)
    try {
    let rtdata = await fetchsync_util("/admin/baseinfo/wldalb", 'POST', {}, "json")

      // 处理时间格式
    rtdata.resultdata.forEach(element => {
      element.create_time = convertISODateTimeToYYYYMMDDHHMMSS(element.create_time)
        element.update_time = convertISODateTimeToYYYYMMDDHHMMSS(element.update_time)
      });

      const processedData = dealnullorundenfined(rtdata.resultdata)
      setAllWldaData(processedData)
      setTableData(processedData)
      setSelectedRowKeys([])
      setSelectedRows([])
      
      console.log('物料档案数据初始化完成，共', processedData.length, '条')
    } catch (error) {
      console.error('查询物料档案失败:', error);
      openNotification_util('查询物料档案失败，请稍后重试');
    }
    setIsLoading(false)
  }

  // 构建物料分类树形结构
  const buildWlflTree = (wlflData) => {
    // 创建根节点
    const rootNode = {
      title: '企业物料总目',
      key: 'ship',
      level: 0,
      data: null, // 根节点不需要具体的分类数据
      children: []
    }

    // 递归构建树形结构
    const buildTreeRecursive = (parentKey, parentLevel) => {
      const children = []
      
      wlflData.forEach(wlfl => {
        // 根据编码规则判断是否为当前父节点的子节点
        let isChild = false
        
        if (parentKey === 'ship') {
          // 根节点的子节点：一级分类 (ship.01, ship.02, ...)
          isChild = wlfl.flbm.match(/^ship\.\d+$/)
        } else {
          // 其他节点的子节点：直接子分类 (parentKey.01, parentKey.02, ...)
          const childPattern = new RegExp(`^${parentKey.replace(/\./g, '\\.')}\\.\\d+$`)
          isChild = childPattern.test(wlfl.flbm)
        }
        
        if (isChild) {
          const node = {
            title: `(${wlfl.flbm})${wlfl.flmc}`,
            key: wlfl.flbm,
            level: parentLevel + 1,
            data: wlfl,
            children: buildTreeRecursive(wlfl.flbm, parentLevel + 1)
          }
          
          // 如果没有子节点，移除children属性
          if (node.children.length === 0) {
            delete node.children
          }
          
          children.push(node)
        }
      })
      
      return children
    }

    // 构建完整的树形结构
    rootNode.children = buildTreeRecursive('ship', 0)
    
    return [rootNode]
  }

  // 树节点选择
  const onTreeSelect = (selectedKeys, info) => {
    if (selectedKeys.length > 0) {
      setSelectedTreeNode(info.node);
      const nodeKey = selectedKeys[0];
      setIsLoading(true);
      try {
        let filteredData = [];
        
        if (nodeKey === 'ship') {
          // 根节点，显示所有物料档案
          filteredData = allWldaData;
          console.log('根节点查询结果:', filteredData.length, '条物料档案');
        } else {
          // 根据选中的分类节点过滤物料档案
          // 使用 LIKE 查询逻辑：如果选中 ship.01，则显示所有 lbbm 以 'ship.01%' 开头的记录
          filteredData = allWldaData.filter(wlda => {
            if (!wlda.lbbm) return false;
            
            // 检查 lbbm 是否以选中的分类编码开头
            return wlda.lbbm.startsWith(nodeKey);
          });
          
          // 找到当前选中的分类节点用于日志显示
          const selectedWlfl = allWlflData.find(wlfl => wlfl.flbm === nodeKey);
          const categoryName = selectedWlfl ? selectedWlfl.flmc : nodeKey;
          console.log(`选中分类 [${categoryName}] 查询结果:`, filteredData.length, '条物料档案');
        }

        setTableData(filteredData);
        setSelectedRowKeys([]);
        setSelectedRows([]);
      } catch (error) {
        console.error('查询物料档案失败:', error);
        openNotification_util('查询物料档案失败');
      }
      setIsLoading(false);
    }
  }

  // 获取节点的直接子分类
  const getDirectChildren = (parentKey) => {
    if (parentKey === 'ship') {
      // 获取一级分类 (ship.01, ship.02, ...)
      return allWlflData.filter(wlfl => wlfl.flbm.match(/^ship\.\d+$/))
    } else {
      // 获取直接子分类 (parentKey.01, parentKey.02, ...)
      const childPattern = new RegExp(`^${parentKey.replace(/\./g, '\\.')}\\.\\d+$`)
      return allWlflData.filter(wlfl => childPattern.test(wlfl.flbm))
    }
  }

  // 获取节点的所有子分类（递归）
  const getAllChildren = (parentKey) => {
    const children = []
    const directChildren = getDirectChildren(parentKey)
    
    directChildren.forEach(child => {
      children.push(child)
      // 递归获取子分类的子分类
      children.push(...getAllChildren(child.flbm))
    })
    
    return children
  }

  // 树节点展开
  const onTreeExpand = (expandedKeys) => {
    setExpandedKeys(expandedKeys);
    setAutoExpandParent(false);
  }

  // 树搜索
  const onTreeSearch = (value) => {
    setSearchValue(value);
    const expandedKeys = getExpandedKeys(treeData, value);
    setExpandedKeys(expandedKeys);
    setAutoExpandParent(true);
  }

  // 获取展开的节点
  const getExpandedKeys = (data, searchValue) => {
    const loop = (data) => {
      return data.reduce((acc, item) => {
        if (item.title.toLowerCase().includes(searchValue.toLowerCase())) {
          acc.push(item.key);
        }
        if (item.children) {
          acc.push(...loop(item.children));
        }
        return acc;
      }, []);
    };
    return loop(data);
  }

  // 处理树状数据，添加搜索高亮
  const getTreeTitle = (title) => {
    if (searchValue && title.toLowerCase().includes(searchValue.toLowerCase())) {
      const index = title.toLowerCase().indexOf(searchValue.toLowerCase());
      const beforeStr = title.substring(0, index);
      const matchStr = title.substring(index, index + searchValue.length);
      const afterStr = title.substring(index + searchValue.length);
      return (
        <span>
          {beforeStr}
          <span style={{ color: '#f50' }}>{matchStr}</span>
          {afterStr}
        </span>
      );
    }
    return title;
  }

  // 处理树状数据
  const processTreeData = (data) => {
    return data.map(item => ({
      ...item,
      title: getTreeTitle(item.title),
      children: item.children ? processTreeData(item.children) : undefined
    }));
  }

  // 刷新
  const handleRefresh = () => {
    queryTreeData()
    queryWldaData()
  }

  // 新增
  const handleAdd = async () => {
    storage.pre_wlda_item = JSON.stringify({ data: {}, type: "add", td: treeData })
    dropByCacheKey("wlda_form")
    setnowroute({...{route:"/shipSRM/baseinfo/wlda_form",title:"物料档案_新增"}})
  }

  // 编辑
  const handleEdit = async (data, type) => {
    storage.pre_wlda_item = JSON.stringify({ type, data })
    dropByCacheKey('wlda_form')
    setnowroute({...{route:"/shipSRM/baseinfo/wlda_form",title:"物料档案_" + `${type == "edit" ? "编辑" : "查看"}`}})
  }

  // 禁用
  const handleDisable = async () => {
    if (selectedRows.length === 0) {
      openNotification_util("请选择要禁用的数据!")
      return
    }
    let rtdata = await fetchsync_util("/admin/baseinfo/disable_wlda", 'POST', { selectedRows }, "json")
    rtdata.rtstatus ? queryWldaData() : 1
  }

  // 启用
  const handleEnable = async () => {
    if (selectedRows.length === 0) {
      openNotification_util("请选择要启用的数据!")
      return
    }
    let rtdata = await fetchsync_util("/admin/baseinfo/enable_wlda", 'POST', { selectedRows }, "json")
    rtdata.rtstatus ? queryWldaData() : 1
  }

  // 导出
  const handleExport = () => {
    let filtercol = JSON.parse(JSON.stringify(columnarr)).filter(item => item.show == true)
    filtercol.forEach(element => {
      element.width = element.width ? element.width / 7 : 10
    });
    useexcelauto(selectedRows, filtercol, '物料档案')
  }

  // 添加一级分类
  const handleAddYjfl = async () => {
    if (!flmc || !flbm) {
      openNotification_util("请填写完整的分类信息!")
      return
    }
    let rtdata = await fetchsync_util("/admin/baseinfo/add_wlfl_yjfl", 'POST', { flbm, flmc, storage: storage }, "json")
    openNotification_util(rtdata.rtmessage)
    queryTreeData()
    setShowYjfl(false)
    setFlmc("")
    setFlbm("")
  }

  // 添加子级分类
  const handleAddZjfl = async () => {
    if (!flmc || !flbm) {
      openNotification_util("请填写完整的分类信息!")
      return
    }
    if (!selectedTreeNode || selectedTreeNode.key === 'ship') {
      openNotification_util("请先选择上级分类!")
      return
    }
    let rtdata = await fetchsync_util("/admin/baseinfo/add_wlfl_zjfl", 'POST', { 
      flbm, 
      flmc,
      storage: storage
    }, "json")
    openNotification_util(rtdata.rtmessage)
    queryTreeData()
    setShowZjfl(false)
    setFlmc("")
    setFlbm("")
  }

  // 生成分类编码
  const generateFlbm = (parentKey) => {
    if (parentKey === 'ship') {
      // 一级分类：ship.01, ship.02, ship.03...
      const existingFirstLevel = allWlflData.filter(item => 
        item.flbm.match(/^ship\.\d+$/)
      )
      
      let maxNum = 0
      existingFirstLevel.forEach(item => {
        const num = parseInt(item.flbm.split('.')[1])
        if (!isNaN(num)) {
          maxNum = Math.max(maxNum, num)
        }
      })
      
      return `ship.${(maxNum + 1).toString().padStart(2, '0')}`
    } else {
      // 子级分类：parentKey.01, parentKey.02...
      const childPattern = new RegExp(`^${parentKey.replace(/\./g, '\\.')}\\.\\d+$`)
      const existingChildren = allWlflData.filter(item => 
        childPattern.test(item.flbm)
      )
      
      let maxNum = 0
      existingChildren.forEach(item => {
        const parts = item.flbm.split('.')
        const num = parseInt(parts[parts.length - 1])
        if (!isNaN(num)) {
          maxNum = Math.max(maxNum, num)
        }
      })
      
      return `${parentKey}.${(maxNum + 1).toString().padStart(2, '0')}`
    }
  }

  // 添加子分类（新方法）
  const handleAddSubCategory = (nodeData) => {
    console.log('添加子分类:', nodeData)
    
    // 生成新的分类编码
    const newFlbm = generateFlbm(nodeData.key)
    
    // 打开新增分类模态框
    setModalType('add')
    setIsCategoryModalOpen(true)
    
    // 设置表单初始值
    form.setFieldsValue({
      flbm: newFlbm,
      flmc: '',
      parentKey: nodeData.key,
      parentTitle: nodeData.key === 'ship' ? '企业物料总目' : nodeData.title.replace(/^\([^)]+\)/, '')
    })
  }

  // 修改分类名称（新方法）
  const handleRenameCategory = (nodeData) => {
    console.log('修改分类名称:', nodeData)
    
    if (nodeData.key === 'ship') {
      openNotification_util("根节点名称不能修改")
      return
    }
    
    // 根据编码规则获取父级信息
    let parentKey = 'ship'
    let parentTitle = '企业物料总目'
    
    if (nodeData.key.includes('.')) {
      const parts = nodeData.key.split('.')
      parts.pop() // 移除最后一部分
      parentKey = parts.join('.')
      
      // 查找父级分类
      const parentCategory = allWlflData.find(item => item.flbm === parentKey)
      if (parentCategory) {
        parentTitle = parentCategory.flmc
      }
    }
    
    setModalType('edit')
    form.setFieldsValue({
      flbm: nodeData.key,
      flmc: nodeData.title.replace(/^\([^)]+\)/, ''), // 移除编码前缀
      parentKey: parentKey,
      parentTitle: parentTitle
    })
    setIsCategoryModalOpen(true)
  }

  // 删除分类（新方法）
  const handleDeleteCategory = async (nodeData) => {
    console.log('删除分类:', nodeData)
    
    if (nodeData.key === 'ship') {
      openNotification_util("根节点不能删除")
      return
    }
    
    // 检查是否可以删除
    const canDelete = await checkCategoryDeletable(nodeData.key)
    if (!canDelete.canDelete) {
      openNotification_util(canDelete.message)
      return
    }
    
    // 确认删除
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除分类 "${nodeData.title.replace(/^\([^)]+\)/, '')}" 吗？此操作不可恢复。`,
      okText: '确定删除',
      okType: 'danger',
      cancelText: '取消',
      onOk: async () => {
        try {
          let rtdata = await fetchsync_util("/admin/baseinfo/delete_wlfl_category", 'POST', { 
            flbm: nodeData.key,
            storage: storage
          }, "json")
          
          if (rtdata.rtstatus) {
            openNotification_util("删除分类成功")
            queryTreeData()
            queryWldaData()
          } else {
            openNotification_util(rtdata.rtmessage || "删除分类失败")
          }
        } catch (error) {
          console.error('删除分类失败:', error)
          openNotification_util("删除分类失败")
        }
      }
    })
  }

  // 检查分类是否可以删除
  const checkCategoryDeletable = async (flbm) => {
    try {
      let rtdata = await fetchsync_util("/admin/baseinfo/check_category_deletable", 'POST', { 
        flbm: flbm
      }, "json")
      
      return {
        canDelete: rtdata.rtstatus,
        message: rtdata.rtmessage || "检查失败"
      }
    } catch (error) {
      console.error('检查分类删除状态失败:', error)
      return {
        canDelete: false,
        message: "检查失败，请稍后重试"
      }
    }
  }

  // 处理分类模态框确认
  const handleCategoryModalOk = async () => {
    try {
      const values = await form.validateFields()
      const { flbm, flmc, parentKey } = values
      
      if (modalType === 'add') {
        // 新增子分类
        let rtdata
        if (parentKey === 'ship') {
          // 新增一级分类
          rtdata = await fetchsync_util("/admin/baseinfo/add_wlfl_yjfl", 'POST', { 
            flbm, 
            flmc,
            storage: storage
          }, "json")
        } else {
          // 新增子级分类 - 不需要传递 sjflbm，后端可以通过编码规则获取
          rtdata = await fetchsync_util("/admin/baseinfo/add_wlfl_zjfl", 'POST', { 
            flbm, 
            flmc,
            storage: storage
          }, "json")
        }
        
        if (rtdata.rtstatus) {
          openNotification_util("新增分类成功")
          setIsCategoryModalOpen(false)
          setModalType('')
          form.resetFields()
          queryTreeData()
        } else {
          openNotification_util(rtdata.rtmessage || "新增分类失败")
        }
      } else if (modalType === 'edit') {
        // 修改分类名称
        const categoryData = allWlflData.find(item => item.flbm === flbm)
        if (!categoryData) {
          openNotification_util("未找到要修改的分类")
          return
        }
        
        let rtdata = await fetchsync_util("/admin/baseinfo/update_wlfl_name", 'POST', { 
          flbm: flbm,
          flmc: flmc,
          storage: storage
        }, "json")
        
        if (rtdata.rtstatus) {
          openNotification_util("修改分类名称成功")
          setIsCategoryModalOpen(false)
          setModalType('')
          form.resetFields()
          queryTreeData()
        } else {
          openNotification_util(rtdata.rtmessage || "修改分类名称失败")
        }
      }
    } catch (error) {
      console.error('表单验证失败:', error)
    }
  }

  // Excel导入处理
  const onImportExcel = (file) => {
    const { files } = file.target;
    const fileReader = new FileReader();
    fileReader.onload = event => {
      try {
        const { result } = event.target;
        const workbook = XLSX.read(result, { type: 'binary' });
        let data = []; // 存储获取到的数据

        for (const sheet in workbook.Sheets) {
          if (workbook.Sheets.hasOwnProperty(sheet)) {
            const sheetData = XLSX.utils.sheet_to_json(workbook.Sheets[sheet]);
            data = data.concat(sheetData);
          }
        }

        var datastr = JSON.stringify(data);
        datastr = datastr.replace(/物料编码/g, "wlbm").replace(/物料名称/g, "wlmc").replace(/规格型号/g, "ggxh").
          replace(/类别/g, "lbbm").replace(/金额/g, "je").replace(/单位/g, "dw")

        setExcelData(JSON.parse(datastr));
        console.log("=============datastr=================", datastr);
      } catch (e) {
        console.log('文件类型不正确');
        openNotification_util('文件类型不正确');
        return;
      }
    };
    fileReader.readAsArrayBuffer(files[0]);
  }

  // 执行Excel导入
  const handleExcelImport = async (data) => {
    setImportloading(true)
    let rtdata = await fetchsync_util("/admin/baseinfo/wlda_import", 'POST', data, "json")
    queryWldaData()
    if (rtdata.resultdata.errorRows.length > 0) {
      setImportError(rtdata.resultdata.errorRows)
      setErrorRows([]);
    }
    else {
      setImportModalVisible(false);
      setImportError([]);
      setErrorRows([]);
      setExcelData(null);
    }
    openNotification_util("导入成功")
    setImportloading(false)
  }

  // 获取导入模板
  const handleGetTemplate = async () => {
      var filtercol = use_wlda_initcolmun_import()
      filtercol.forEach(element => {
        element.width = element.width ? element.width / 7 : 10
      });
      useexcelauto([], filtercol, '物料档案导入模板')
    }

  return (
    <div style={{
      height: "94%", backgroundColor: `#F1F1F1`, right: "1%", top: "4vh", overflow: "hidden",
      backgroundSize: "100% 100%", width: collapsed ? "94%" : "84%", position: "absolute", color: "white", fontSize: "0.8rem"
    }}>
      <div style={styles.kshcontainer}>
        <Row gutter={16} style={{ height: '100%' }}>
          {/* 左侧物料分类树形区域 */}
          <Col span={6} style={{ height: '100%', borderRight: '1px solid #f0f0f0' }}>
            <Card 
              title={
                <div style={{ display: 'flex', alignItems: 'center' }}>
                  <MenuOutlined style={{ marginRight: 8 }} />
                  物料分类结构
                </div>
              }
              size="small" 
              style={{ height: '100%' }}
              bodyStyle={{ height: 'calc(100% - 57px)', overflow: 'auto', padding: '8px' }}
            >
              <Search
                style={{ marginBottom: 8 }}
                placeholder="搜索分类"
                onSearch={onTreeSearch}
                allowClear
              />
              {isLoading ? (
                <div style={{ textAlign: 'center', padding: '20px' }}>
                  <Spin />
                </div>
              ) : (
                <Tree
                  showLine
                  showIcon
                  expandedKeys={expandedKeys}
                  autoExpandParent={autoExpandParent} 
                  selectedKeys={selectedTreeNode ? [selectedTreeNode.key] : []}
                  onExpand={onTreeExpand}
                  onSelect={onTreeSelect}
                  treeData={processTreeData(treeData)}
                  titleRender={(nodeData) => {
                    const isSelected = selectedTreeNode?.key === nodeData.key;
                    return (
                      <div 
                        style={{ 
                          display: 'flex',
                          alignItems: 'center', 
                          width: '100%',
                          padding: '4px 8px',
                          borderRadius: '4px',
                          backgroundColor: isSelected ? '#e6f7ff' : 'transparent',
                          transition: 'all 0.3s'
                        }}
                        onMouseEnter={(e) => {
                          e.currentTarget.style.backgroundColor = '#f5f5f5';
                          const actionBtn = e.currentTarget.querySelector('.node-action-button');
                          if(actionBtn) actionBtn.style.visibility = 'visible';
                        }}
                        onMouseLeave={(e) => {
                          e.currentTarget.style.backgroundColor = isSelected ? '#ffebe6' : 'transparent';
                          const actionBtn = e.currentTarget.querySelector('.node-action-button');
                          if(actionBtn) actionBtn.style.visibility = 'hidden';
                        }}
                      >
                        <span style={{ flex: 1 }}>
                          {nodeData.title}
                        </span>
                        <div className="node-action-button" style={{visibility: 'hidden'}}>
                          <Dropdown
                            trigger={['click']}
                            menu={{
                              items: [
                                {
                                  key: '1',
                                  label: '添加子分类',
                                  icon: <PlusSquareOutlined />,
                                  onClick: () => handleAddSubCategory(nodeData)
                                },
                                {
                                  key: '2',
                                  label: '修改名称', 
                                  icon: <EditOutlined />,
                                  onClick: () => handleRenameCategory(nodeData)
                                },
                                {
                                  key: '3',
                                  label: '删除分类', 
                                  icon: <MinusSquareOutlined />,
                                  onClick: () => handleDeleteCategory(nodeData)
                                }
                              ]
                            }}
                          >
                            <Button
                              type="text" 
                              size="small"
                              icon={<EllipsisOutlined />}
                              onClick={e => e.stopPropagation()}
                            />
                          </Dropdown>
                        </div>
                      </div>
                    );
                  }}
                />
              )}
              
              {/* 分类管理按钮 */}
              {/* <div style={{ marginTop: '14px', display: 'flex', flexDirection: 'column', gap: '8px' }}>
                <Button
                  size="small"
                  style={{ backgroundColor: "#a91f24", color: "white" }}
                  onClick={() => setShowYjfl(true)}
                >
                  <PlusSquareOutlined />新增一级分类
                </Button>
                <Button
                  size="small"
                  style={{ backgroundColor: "white", color: "#a91f24", border: "1px solid #a91f24" }}
                  onClick={() => {
                    if (selectedTreeNode && selectedTreeNode.key !== '/wlda') {
                      setShowZjfl(true)
                    } else {
                      openNotification_util("请先选择上级分类")
                    }
                  }}
                >
                  <PlusSquareOutlined />新增子级分类
                </Button>
              </div> */}
            </Card>
          </Col>

          {/* 右侧物料档案管理区域 */}
          <Col span={18} style={{ height: '100%' }}>
            <Card 
              title={
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                  <span>
                    <ProfileOutlined style={{ marginRight: 8 }} />
                    {selectedTreeNode && selectedTreeNode.key !== 'ship' ? selectedTreeNode.title : '企业物料总目'}
                  </span>
                  <div style={{ display: 'flex', gap: '8px', flexWrap: 'wrap' }}>
                    <Button 
                      size="small"
                      style={{ backgroundColor: "white", color: "#a91f24", fontWeight: "800" }}
                      onClick={handleAdd}
                    >
                      <PlusSquareOutlined />新增物料
                    </Button>
                    <Button 
                      size="small"
                      style={{ backgroundColor: "white", color: "#a91f24", fontWeight: "800" }}
                      onClick={handleDisable}
                    >
                      <MinusSquareOutlined />禁用物料
                    </Button>
                    <Button 
                      size="small"
                      style={{ backgroundColor: "#a91f24", color: "white", fontWeight: "800" }}
                      onClick={handleEnable}
                    >
                      <PlusSquareOutlined />启用物料
                    </Button>
                    <Button 
                      size="small"
                      style={{ backgroundColor: "#a91f24", color: "white", fontWeight: "800" }}
                      onClick={() => setImportModalVisible(true)}
                    >
                      <CloudUploadOutlined />批量导入
                    </Button>
                    <Button size="small" onClick={handleRefresh}>
                      <ReloadOutlined />刷新
                    </Button>
                    <Button size="small" onClick={handleExport}>
                      <FileExcelOutlined />导出
                    </Button>
                  </div>
                </div>
              }
              style={{ height: '100%' }} 
              bodyStyle={{ height: 'calc(100% - 57px)', padding: '6px' }}
            >
              {/* 表格设置按钮区域 */}
              <div style={{ 
                marginBottom: '10px', 
                display: 'flex', 
                justifyContent: 'flex-end', 
                alignItems: 'center'
              }}>
                <IconFont 
                  type="setting" 
                  style={{ fontSize: "1.5rem", cursor: 'pointer' }}
                  onClick={() => setIsTableSettingModalOpen(true)} 
                />
              </div>

              {/* 表格设置组件 */}
              {ifshow && (
                <Sortable 
                  tableColnum={columnarr} 
                  handleTableColomn={(data) => { setColumnarr(data); }}
                  storageName={"Pc_wlda_list"} 
                  open={isTableSettingModalOpen} 
                  handleOpen={(data) => { setIsTableSettingModalOpen(data); }}
                  initSize={initSize} 
                  handleInitSize={(data) => { setInitSize(data); storage['Pc_wlda_list_initsize'] = data; }}
                />
              )}

              {/* 表格区域 */}
              {isLoading ? (
                <div style={{ textAlign: 'center', padding: '50px' }}>
                  <Spin />
                </div>
              ) : (
                <Resizeable_table__hook
                  tabledata={tableData}
                  tablecolnum={columnarr}
                  width="100%"
                  sfdoubleclick={false}
                  ifhiddencchangeselecttype={true}
                  selectedRows={selectedRows}
                  selectedRowKeys={selectedRowKeys}
                  defaultPageSize={12}
                  bordered
                  showCz={{ showEdit: true }}
                  
                  handleEdit={(data) => handleEdit(data, "edit")}
                  
                  scroll={{ y: 'calc(100vh - 280px)', x: initSize * 1250 }}
                  handleselectson={(selectedRows, selectedRowKeys) => {
                    setSelectedRows(selectedRows);
                    setSelectedRowKeys(selectedRowKeys);
                  }}
                />
              )}
            </Card>
          </Col>
        </Row>
      </div>

     

      {/* 导入模态框 */}
          <Modal
            title="选择导入文件"
        open={importModalVisible}
            onOk={() => {
              if (excelData && excelData.length > 0) {
            handleExcelImport(excelData);
              } else {
                openNotification_util("请先选择并解析Excel文件");
                setImportError([]);
              }
            }}
            onCancel={() => {
              setImportModalVisible(false);
              setImportError([]);
              setExcelData(null);
            }}
          >
        {importloading ? (
          <div style={{ textAlign: 'center', color: "#14d9cc" }}>
                <Spin />
                <div style={{ fontSize: "0.8rem", fontWeight: "500", color: "black" }}>导入中，请稍后...</div>
          </div>
        ) : (
          <>
            <Button 
              style={{ backgroundColor: "white", color: "#a91f24", fontWeight: "800", marginBottom: '14px' }}
              onClick={handleGetTemplate}
            >
              <FileExcelOutlined /> 获取导入模板
            </Button>
                <br />
                <input
                  type='file'
                  accept='.xlsx, .xls'
                  onChange={(e) => {
                    onImportExcel(e);
                    e.target.value = null;
                  }}
                />
                {excelData && <div style={{ marginTop: 16 }}>已解析 {excelData.length} 条数据</div>}
                {importError.length > 0 && (
                  <div style={{marginTop: 16, color: 'red'}}>
                    以下行物料编码已存在:
                    <ul>
                      {importError.map(err => (
                        <li key={err.rowNumber}>第{err.rowNumber}行物料编码：{err.wlbm} 已存在</li>
                      ))}
                    </ul>
                  </div>
                )} 
          </>
        )}
          </Modal>

      {/* 分类管理模态框 */}
      <Modal
        title={modalType === 'add' ? '新增子分类' : '修改分类名称'}
        open={isCategoryModalOpen}
        onOk={handleCategoryModalOk}
        onCancel={() => {
          setIsCategoryModalOpen(false)
          form.resetFields()
          setModalType('')
        }}
        destroyOnClose
      >
        <Form
          form={form}
          layout="vertical"
          initialValues={{
            flbm: '',
            flmc: '',
            parentKey: '',
            parentTitle: ''
          }}
        >
          <Form.Item
            name="parentKey"
            hidden
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="parentTitle"
            hidden
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="上级分类"
            style={{ marginBottom: '8px' }}
          >
            <Input 
              value={form.getFieldValue('parentTitle') || '企业物料总目'} 
              disabled 
              style={{ backgroundColor: '#f5f5f5' }}
            />
          </Form.Item>
          <Form.Item
            name="flbm"
            label="分类编码"
            rules={[
              { required: true, message: '请输入分类编码' },
              { pattern: /^[a-zA-Z0-9.]+$/, message: '分类编码只能包含字母、数字和点号' }
            ]}
          >
            <Input 
              placeholder="请输入分类编码"
              disabled={modalType === 'edit'} // 编辑时不允许修改编码
              style={modalType === 'edit' ? { backgroundColor: '#f5f5f5' } : {}}
            />
          </Form.Item>
          <Form.Item
            name="flmc"
            label="分类名称"
            rules={[
              { required: true, message: '请输入分类名称' },
              { max: 50, message: '分类名称不能超过50个字符' }
            ]}
          >
            <Input placeholder="请输入分类名称" />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}

export default Wlda_list

const styles = {
  kshcontainer: {
    width: "98%", 
    height: "95%", 
    position: "absolute", 
    top: "3%", 
    left: "1%", 
    backgroundColor: "white", 
    color: "black",
    borderRadius: "10px",
    padding: "14px"
  }
}



